﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

using AjaxControlFramework.Compilation;
using AjaxControlFramework.Reflection;

namespace AjaxControlFramework.Compilation
{
    public class JsxScriptHandler : IHttpHandler
    {
        //------// Properties \\--------------------------------------------\\
        public bool IsReusable
        {
            get { return true; }
        }
        //------\\ Properties //--------------------------------------------//



        //------// Fields \\------------------------------------------------\\
        private static Dictionary<string, IHttpHandler> ScriptHandlers = new Dictionary<string, IHttpHandler>();
        //------\\ Fields //------------------------------------------------//



        //------// Constructors \\------------------------------------------\\
        public JsxScriptHandler()
        { }
        //------\\ Constructors //------------------------------------------//



        //------// Methods \\-----------------------------------------------\\
        public static void AddScriptHandler(JsxScript script)
        {
            if (!ScriptHandlers.ContainsKey(script.ScriptName))
            {
                object handler = null;

                if (TypeCache.CreateObject(script.HandlerType, out handler))
                {
                    IHttpHandler httpHandler = handler as IHttpHandler;

                    if (httpHandler != null)
                    {
                        ScriptHandlers.Add(script.ScriptName, httpHandler);
                    }
                }
            }
        }


        public void ProcessRequest(HttpContext context)
        {
            string scriptName = Path.GetFileNameWithoutExtension(context.Request.FilePath);

            IHttpHandler scriptHandler = null;

            if (ScriptHandlers.TryGetValue(scriptName, out scriptHandler))
            {
                scriptHandler.ProcessRequest(context);
            }

            context.Response.End();
        }
        //------\\ Methods //-----------------------------------------------//
    }
}